package com.zc.app.shiro.session.dao;

import com.zc.app.shiro.utils.JdbcTemplateUtils;
import com.zc.app.shiro.utils.SerializableUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zc on 2016/7/19.
 */
public class MySessionDAO extends CachingSessionDAO {

    private JdbcTemplate jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();

    @Override
    protected void doUpdate(Session session) {
        if(session instanceof ValidatingSession
                && !((ValidatingSession)session).isValid()) {
            return;
        }
        String sql = "UPDATE SESSIONS SET SESSION=? WHERE ID=? ";
//        jdbcTemplate.update(sql,SerializableUtils.serialize(session), session.getId());

    }

    @Override
    protected void doDelete(Session session) {
        String sql = "DELETE FROM SESSIONS WHERE ID=? ";
//        jdbcTemplate.update(sql, session.getId());
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        String sql = "INSERT INTO SESSIONS(ID, SESSION) VALUES (?, ?)";
//        jdbcTemplate.update(sql, sessionId, SerializableUtils.serialize(session));
        return session.getId();
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        String sql = "SELECT SESSION FROM SESSIONS WHERE ID=? ";
//        List<String> sessionStrList = jdbcTemplate.queryForList(sql, String.class, sessionId);
//        if(sessionStrList.size() == 0) return null;
//        return SerializableUtils.deserialize(sessionStrList.get(0));
        return null;
    }

}
